﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Webdiyer.WebControls.Mvc;
using System.IO;
using System.Text;
namespace MvcWeb.Controllers
{
    public class InventoryController : BaseController
    {
        //
        // GET: /Inventory/

        public ActionResult Index(MvcWeb.ViewModels.Inventory.InventoryModel viewModel, int pageindex = 1, int pageSize = 20)
        {
            var iquery = db.AssetInventory.AsQueryable();

            if (viewModel.conditionModel != null)
            {
                if (viewModel.conditionModel.AssetInventoryName != null)
                {
                    iquery = iquery.Where(m => m.AssetInventoryName == viewModel.conditionModel.AssetInventoryName);
                }
                if (viewModel.conditionModel.InventoryState != null)
                {
                    iquery = iquery.Where(m => m.AssetInventoryState == viewModel.conditionModel.InventoryState);
                }
                if (viewModel.conditionModel.InventoryMember != null)
                {
                    iquery = iquery.Where(m => m.AssetInventoryMember == viewModel.conditionModel.InventoryMember);
                }
                if (viewModel.conditionModel.InventoryCheckMember != null)
                {
                    iquery = iquery.Where(m => m.AssetInventoryCheckMember == viewModel.conditionModel.InventoryCheckMember);
                }
                if (viewModel.conditionModel.InventoryStartTime != null)
                {
                    iquery = iquery.Where(m => m.AssetInventoryStartDateTime >= viewModel.conditionModel.InventoryStartTime);
                }
                if (viewModel.conditionModel.InventoryEndTime != null)
                {
                    iquery = iquery.Where(m => m.AssetInventoryEndDateTime <= viewModel.conditionModel.InventoryEndTime);
                }
            }

            iquery = iquery.OrderByDescending(m => m.AssetInventoryID);

            var list = iquery.ToPagedList(pageindex, pageSize);

            MvcWeb.ViewModels.Inventory.InventoryModel model = new ViewModels.Inventory.InventoryModel();
            model.inventoryModelList = list;
            model.conditionModel = new ViewModels.Inventory.InvetorySearchConditonModel();

            var users = db.aspnet_Users.ToList().ToDictionary(a => a.UserId, b => b.UserName);
            users.Add(new Guid(), "");
            ViewData["memberIDDict"] = users;

            ViewData["inventoryStatus"] = MvcWeb.EAMEnum.EAMEnumExt.ToDictory<MvcWeb.EAMEnum.InventoryStatus>();


            return View(model);
        }

        public ActionResult Edit(int id = -1)
        {
            EAM.Model.AssetInventory model = null;
            if (id == -1)
            {
                model = new EAM.Model.AssetInventory();
                var tmpAssetInventory = db.TmpAssetInventory.ToList();

                //foreach (EAM.Model.TmpAssetInventory tmpModel in tmpAssetInventory)
                //{
                //    db.TmpAssetInventory.Remove(tmpModel);
                //}
                tmpAssetInventory.RemoveAll(m => m.AssetLabel != "");
                //tmpAssetInventory.RemoveAll(m => m.AddDateTimes < DateTime.Now);
                //tmpAssetInventory.RemoveAll //删除临时表中的数据。
                db.SaveChanges();
            }
            else
            {
                model = db.AssetInventory.Find(id);
            }

            //ViewData["inventoryStatus"] = new SelectList(MvcWeb.EAMEnum.EAMEnumExt.ToListItem<MvcWeb.EAMEnum.InventoryStatus>(), "value", "text");

            ViewData["inventoryStatus"] = MvcWeb.EAMEnum.EAMEnumExt.ToDictory<MvcWeb.EAMEnum.InventoryStatus>();


            var users = db.aspnet_Users.ToList().ToDictionary(a => a.UserId, b => b.UserName);
            users.Add(new Guid(), "");
            ViewData["memberIDDict"] = users;

            return View(model);
        }

        [HttpPost]
        public ActionResult Edit(int id, EAM.Model.AssetInventory viewModel)
        {
            var user = System.Web.Security.Membership.GetUser();
            var guid = (Guid)user.ProviderUserKey;

            if (id == -1)
            {
                //添加关联信息
                EAM.Model.AssetInventory model = new EAM.Model.AssetInventory()
                {
                    AssetInventoryStartDateTime = viewModel.AssetInventoryStartDateTime,
                    AssetInventoryEndDateTime = viewModel.AssetInventoryEndDateTime,
                    AssetInventoryCheckMember = viewModel.AssetInventoryCheckMember,
                    AssetInventoryDescript = viewModel.AssetInventoryDescript,
                    AssetInventoryMember = viewModel.AssetInventoryMember,
                    AssetInventoryName = viewModel.AssetInventoryName,
                    AssetInventoryState = viewModel.AssetInventoryState,
                    AssetInventorySum = viewModel.AssetInventorySum
                };
                db.AssetInventory.Add(model);
            }
            else
            {
                var model = db.AssetInventory.Find(id);
                db.AssetInventory.Attach(model);

                model.AssetInventoryStartDateTime = viewModel.AssetInventoryStartDateTime;
                model.AssetInventoryEndDateTime = viewModel.AssetInventoryEndDateTime;
                model.AssetInventoryCheckMember = viewModel.AssetInventoryCheckMember;
                model.AssetInventoryDescript = viewModel.AssetInventoryDescript;
                model.AssetInventoryMember = viewModel.AssetInventoryMember;
                model.AssetInventoryName = viewModel.AssetInventoryName;
                model.AssetInventoryState = viewModel.AssetInventoryState;
                model.AssetInventorySum = viewModel.AssetInventorySum;
            }

            db.SaveChanges();

            MvcWeb.ViewModels.Inventory.InventoryModel reViewModel = new ViewModels.Inventory.InventoryModel();
            // return RedirectToAction("Index", new { viewModel = reViewModel });

            return Redirect("/Inventory/Index");
        }

        public ActionResult InventoryAssetID(string assetIDs)
        {
            return View();
        }

        /// <summary>
        /// 资产盘点标签上传的文件
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult InventUploadIndex(int id)
        {
            //MvcWeb.ViewModels.Inventory.InventoryDetailIDs model = new ViewModels.Inventory.InventoryDetailIDs();
            //model.AssetInventoryID = id;
            //model.inventoryDetailIDs = "";

            ViewData["inventoryID"] = id;
            return View();
        }

        /// <summary>
        /// 资产盘点上传内容
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult InventUpload(FormCollection form, int inventID)
        {
            if (Request.Files.Count == 0)
            {
                //Request.Files.Count 文件数为0上传不成功　　　
                return RedirectToAction("InventUploadIndex", new { id = inventID });
            }
            var file = Request.Files[0];
            string saveFile = "Inventory_" + DateTime.Now.ToString("yyyyMMddHH") + ".txt";

            if (file.ContentLength == 0)
            {
                //文件大小大（以字节为单位）为0时，做一些操作　
                return RedirectToAction("InventUploadIndex", new { id = inventID });
            }
            else
            {
                //文件大小不为0　　
                HttpPostedFileBase _file = Request.Files[0];
                //保存成自己的文件全路径,newfile就是你上传后保存的文件,　　　
                //服务器上的UpLoadFile文件夹必须有读写权限

                _file.SaveAs(Server.MapPath(@saveFile));
            }

            ////string inventoryId= "";
            //StringBuilder inventoryId = new StringBuilder();
            //using (StreamReader sr = System.IO.File.OpenText(Server.MapPath(@saveFile)))
            //{
            //    //string line = "";
            //    string str = "";

            //    while ((str = sr.ReadLine()) != null)
            //    {
            //        string strLabel = str.Replace(",", "").Trim();
            //        if (!strLabel.Equals(""))
            //            inventoryId.Append(strLabel);
            //            //inventoryId += strLabel + "\r\n";
            //    }
            //}

            //MvcWeb.ViewModels.Inventory.InventoryDetailIDs model = new ViewModels.Inventory.InventoryDetailIDs();
            //model.AssetInventoryID = viewModel.AssetInventoryID;
            //model.inventoryDetailIDs = inventoryId;

            return RedirectToAction("InputInventIDs", new { id = inventID, filePath = Server.MapPath(@saveFile) });
        }


        public ActionResult InputInventIDs(int id, string filePath)// inventIds)
        {
            StringBuilder inventoryId = new StringBuilder();
            using (StreamReader sr = System.IO.File.OpenText(@filePath))
            {
                string str = "";
                string[] spliteChar = new string[] {" " }; 
                while ((str = sr.ReadLine()) != null)
                {
                    string strLabel = str.Replace(",", "").Trim();//扫描枪是否有数量，是如何分开识别的
                    string strCount = (strLabel.Split(spliteChar, StringSplitOptions.None).ToArray())[1]; 
                    if (!strLabel.Equals(""))
                    {
                        inventoryId.Append(strLabel + "\r\n");

                        EAM.Model.TmpAssetInventory tmpModel = db.TmpAssetInventory.Where(m => m.AssetLabel == strLabel).FirstOrDefault();
                        if (tmpModel == null)
                        {
                            tmpModel = new EAM.Model.TmpAssetInventory();
                            tmpModel.AssetLabel = strLabel;
                            tmpModel.AddDateTimes = DateTime.Now;
                            tmpModel.AssetCount = strCount ==null ? 1 : int.Parse(strCount);
                            db.TmpAssetInventory.Add(tmpModel);
                        }
                    }
                }
            }

            db.SaveChanges();//增加信息到临时表中，以防以后使用

            MvcWeb.ViewModels.Inventory.InventoryDetailIDs model = new ViewModels.Inventory.InventoryDetailIDs();
            model.AssetInventoryID = id;
            model.inventoryDetailIDs = inventoryId.ToString();
            return View(model);
        }

        [HttpPost]
        public ActionResult InputInventIDs(MvcWeb.ViewModels.Inventory.InventoryDetailIDs viewModel)
        {
            var user = System.Web.Security.Membership.GetUser();
            var guid = (Guid)user.ProviderUserKey;

            string ids = viewModel.inventoryDetailIDs;
            var iquery = db.AssetManager.AsQueryable();

            string[] strSplit = new string[] { "\r\n" };
            string[] i_ids = ids.Split(strSplit, StringSplitOptions.RemoveEmptyEntries).ToArray();
            iquery = iquery.Where(m => i_ids.Contains(m.AssetLabel));

            iquery = iquery.OrderBy(m => m.AssetID);

            var model = iquery.ToList();

            var existInventDetailList = db.AssetInventoryDetail.Where(m => m.AssetInventoryID == viewModel.AssetInventoryID).ToList();

            foreach (EAM.Model.AssetManager assetModel in model)
            {
                //EAM.Model.AssetInventoryDetail existInventDetail = existInventDetailList.Where(m => m.InventoryLabel == assetModel.AssetLabel).FirstOrDefault();

                EAM.Model.AssetInventoryDetail existInventDetail = existInventDetailList.Where(m => m.AssetLabel == assetModel.AssetLabel).FirstOrDefault();

                if (existInventDetail == null)
                {
                    EAM.Model.AssetInventoryDetail inventDetailModel = new EAM.Model.AssetInventoryDetail();
                    db.AssetInventoryDetail.Add(inventDetailModel);
                    inventDetailModel.AssetBarcode = assetModel.AssetBarcode;
                    inventDetailModel.AssetLabel = assetModel.AssetLabel;
                    inventDetailModel.AssetExists = true;
                    inventDetailModel.AssetID = assetModel.AssetID;
                    inventDetailModel.AssetInventoryID = viewModel.AssetInventoryID;
                    inventDetailModel.InventoryCustodyAddress = assetModel.AssetCustodyAddress;
                    inventDetailModel.AssetName = assetModel.AssetName;

                    int days = assetModel.AssetBuyTime != null ? (DateTime.Now - (DateTime)assetModel.AssetBuyTime).Days : 365;
                    int years = (int)Math.Ceiling(days * 1.0 / 365);
                    inventDetailModel.AssetWorth = assetModel.AssetPurchaseCost != 0 ? assetModel.AssetPurchaseCost * (1 - (assetModel.AssetDepriciationRate != null ? assetModel.AssetDepriciationRate : (decimal)0.3) * years) : 0;//计算这次盘点该资产的价值。
                    db.AssetManager.Attach(assetModel);
                    assetModel.AssetInventoryExists = true;
                    assetModel.AssetInventoryTime = DateTime.Now;
                    assetModel.AssetInventoryMemberIDs = guid;

                    db.SaveChanges();
                }
            }

            return RedirectToAction("InventoryDetail", new { id = viewModel.AssetInventoryID });

        }

        /// <summary>
        /// 资产盘点明细
        /// </summary>
        /// <param name="id"></param>
        /// <param name="pageindex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public ActionResult InventoryDetail(int id = -1, int pageindex = 1, int pageSize = 20)
        {
            var iquery = db.AssetManager.GroupJoin(db.AssetInventoryDetail.Where(m => m.AssetInventoryID == id),
                    manager => manager.AssetLabel,
                    iDetail => iDetail.AssetLabel,
                    (manager, iDetail) =>
                        new MvcWeb.ViewModels.Inventory.InventoryDetailViewModel
                        {
                            AssetID = manager.AssetID,
                            AssetName = manager.AssetName,
                            AssetBarcode = manager.AssetBarcode,
                            AssetLabel = manager.AssetLabel,
                            AssetCustodyAddress = manager.AssetCustodyAddress,
                            AssetPurchaseCost = manager.AssetPurchaseCost,
                            AssetInventoryDetailID = iDetail.Select(m => m.AssetInventoryDetailID).FirstOrDefault(),
                            InventoryCustodyAddress = iDetail.Select(m => m.InventoryCustodyAddress).FirstOrDefault(),
                            InventoryExists = iDetail.Select(m => m.AssetExists).FirstOrDefault(),
                            InventoryHandleAdvice = iDetail.Select(m => m.InventoryHandleAdvice).FirstOrDefault(),
                            InventoryHandleResult = iDetail.Select(m => m.InventoryHandleResult).FirstOrDefault(),
                            InventoryRemark = iDetail.Select(m => m.InventoryRemark).FirstOrDefault(),
                            AssetWorth = iDetail.Select(m => m.AssetWorth).FirstOrDefault()
                        }
                ).OrderBy(m => m.InventoryExists);// .OrderBy(m => m.AssetInventoryDetailID);

            var list = iquery.ToPagedList(pageindex, pageSize);
            MvcWeb.ViewModels.Inventory.InventoryDetailModel model = new ViewModels.Inventory.InventoryDetailModel();
            model.inventoryDetailModelList = list;
            model.InventoryID = id;

            return View(model);
        }

        public ActionResult editInventDetail(int id)
        {
            var model = db.AssetInventoryDetail.Find(id);

            return View(model);
        }

        [HttpPost]
        public ActionResult editInventDetail(int id, EAM.Model.AssetInventoryDetail viewModel)
        {
            var model = db.AssetInventoryDetail.Find(id);

            db.AssetInventoryDetail.Attach(model);

            model.InventoryCustodyAddress = viewModel.InventoryCustodyAddress;
            model.InventoryHandleAdvice = viewModel.InventoryHandleAdvice;
            model.InventoryHandleResult = viewModel.InventoryHandleResult;
            model.InventoryRemark = viewModel.InventoryRemark;
            model.AssetWorth = viewModel.AssetWorth;
            db.SaveChanges();

            return RedirectToAction("InventoryDetail", new { id = viewModel.AssetInventoryID });
        }


        // GET: /Inventory/checkInvent/
        public ActionResult checkInvent(string id)
        {
            var user = System.Web.Security.Membership.GetUser();
            var guid = (Guid)user.ProviderUserKey;

            var model = db.AssetInventory.Find(int.Parse(id));
            db.AssetInventory.Attach(model);

            model.AssetInventoryCheckMember = guid;
            model.AssetInventoryEndDateTime = DateTime.Now;
            model.AssetInventoryCheckDateTime = DateTime.Now;

            db.SaveChanges();

            return RedirectToAction("InventoryDetail", new { id = id });
        }

        public ActionResult del(int id)
        {
            var model = db.AssetInventory.Find(id);
            db.AssetInventory.Attach(model);//.Remove(model);
            model.AssetInventoryState = (int)MvcWeb.EAMEnum.InventoryStatus.撤销;
            db.SaveChanges();
            return Json(true);
        }





        /// <summary>
        /// 资产盘点分类情况
        /// </summary>
        /// <param name="id"></param>
        /// <param name="pageindex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public ActionResult InventoryCategoryDetail(int id,  int pageindex = 1, int pageSize = 20)
        {

            var assetIQuery = db.AssetManager.GroupJoin(db.AssetInventoryDetail.Where(m => m.AssetInventoryID == id),
                    manager => manager.AssetLabel,
                    iDetail => iDetail.AssetLabel,
                    (manager, iDetail) =>
                        new MvcWeb.ViewModels.Inventory.InventoryDetailViewModel
                        {
                            AssetID = manager.AssetID,
                            AssetName = manager.AssetName,
                            AssetBarcode = manager.AssetBarcode,
                            AssetLabel = manager.AssetLabel,
                            AssetCustodyAddress = manager.AssetCustodyAddress,
                            AssetPurchaseCost = manager.AssetPurchaseCost,
                            AssetCID = manager.AssetCID,
                            AssetStatus = manager.AssetStatus,
                            AssetOut = manager.AssetOut,
                            AssetFrom =  manager.AssetFrom,                               
                            AssetInventoryDetailID = iDetail.Select(m => m.AssetInventoryDetailID).FirstOrDefault(),
                            InventoryCustodyAddress = iDetail.Select(m => m.InventoryCustodyAddress).FirstOrDefault(),
                            InventoryExists = iDetail.Select(m => m.AssetExists).FirstOrDefault(),
                            InventoryHandleAdvice = iDetail.Select(m => m.InventoryHandleAdvice).FirstOrDefault(),
                            InventoryHandleResult = iDetail.Select(m => m.InventoryHandleResult).FirstOrDefault(),
                            InventoryRemark = iDetail.Select(m => m.InventoryRemark).FirstOrDefault(),
                            AssetWorth = iDetail.Select(m => m.AssetWorth).FirstOrDefault(),
                            InventoryAssetCount = iDetail.Select(m=>m.AssetCount).FirstOrDefault()
                        }
                );//.OrderBy(m => m.AssetInventoryDetailID);

            var cateIQuery = db.AssetCategory.AsQueryable().OrderBy(m=>m.CategoryID);

            var catelist = cateIQuery.ToPagedList(pageindex, pageSize);

            List<MvcWeb.ViewModels.Inventory.InventoryCateDetailViewModel> retViewList = new List<ViewModels.Inventory.InventoryCateDetailViewModel>();

            foreach (EAM.Model.AssetCategory cateModel in catelist)
            {
                //var catAssetModel = assetIQuery.Where( m => m.AssetCID  == cateModel.CategoryID).ToList();
                MvcWeb.ViewModels.Inventory.InventoryCateDetailViewModel viewModel = new MvcWeb.ViewModels.Inventory.InventoryCateDetailViewModel();
                viewModel.CategoryID = cateModel.CategoryID;
                viewModel.CategoryName = cateModel.CategoryName;
                
                viewModel.CategoryAllCount = assetIQuery.Where(m=>m.AssetCID == cateModel.CategoryID) .Count();
                //viewModel.CategoryAllMoney = assetIQuery.Where(m=>m.AssetCID == cateModel.CategoryID).Sum(m => m.AssetPurchaseCost);
                viewModel.CategorySourceAllMoney = assetIQuery.Where(m => m.AssetCID == cateModel.CategoryID).Sum(m => m.AssetPurchaseCost);
                viewModel.CategoryAllMoney = assetIQuery.Where(m => m.AssetCID == cateModel.CategoryID).Sum(m => m.AssetWorth);

                viewModel.CategoryDestoryCount = assetIQuery.Where(m => m.AssetCID == cateModel.CategoryID && m.AssetStatus == (int)MvcWeb.EAMEnum.AssetStatusEnum.销毁).Count();
                viewModel.CategoryDestoryMoney = assetIQuery.Where(m => m.AssetCID == cateModel.CategoryID && m.AssetStatus == (int)MvcWeb.EAMEnum.AssetStatusEnum.销毁).Sum(m => m.AssetWorth);

                    viewModel.CategoryStoredCount = assetIQuery.Where(m => m.AssetCID == cateModel.CategoryID && m.AssetStatus == (int)MvcWeb.EAMEnum.AssetStatusEnum.库存).Count();
                    viewModel.CategoryStoredMoney = assetIQuery.Where(m => m.AssetCID == cateModel.CategoryID && m.AssetStatus == (int)MvcWeb.EAMEnum.AssetStatusEnum.库存).Sum(m => m.AssetWorth);

                viewModel.CategoryUsedCount = assetIQuery.Where(m => m.AssetCID == cateModel.CategoryID && m.AssetStatus == (int)MvcWeb.EAMEnum.AssetStatusEnum.使用中).Count();
                viewModel.CategoryUsedMoney = assetIQuery.Where(m => m.AssetCID == cateModel.CategoryID && m.AssetStatus == (int)MvcWeb.EAMEnum.AssetStatusEnum.使用中).Sum(m => m.AssetWorth);

                viewModel.CategoryWorthlessCount = assetIQuery.Where(m => m.AssetCID == cateModel.CategoryID && m.AssetStatus == (int)MvcWeb.EAMEnum.AssetStatusEnum.报废).Count();
                viewModel.CategoryWorthlessMoney = assetIQuery.Where(m => m.AssetCID == cateModel.CategoryID && m.AssetStatus == (int)MvcWeb.EAMEnum.AssetStatusEnum.报废).Sum(m => m.AssetWorth);

                viewModel.CategoryPresentCount = assetIQuery.Where(m => m.AssetCID == cateModel.CategoryID && m.AssetStatus == (int)MvcWeb.EAMEnum.AssetOutEnum.捐赠).Count();
                viewModel.CategoryPresentMoney = assetIQuery.Where(m => m.AssetCID == cateModel.CategoryID && m.AssetStatus == (int)MvcWeb.EAMEnum.AssetOutEnum.捐赠).Sum(m => m.AssetWorth);

                viewModel.CategoryInventoryCount = assetIQuery.Where(m => m.AssetCID == cateModel.CategoryID && m.AssetInventoryDetailID != 0).Count();
                viewModel.CategoryInventoryMoney = assetIQuery.Where(m => m.AssetCID == cateModel.CategoryID && m.AssetInventoryDetailID != 0).Sum(m => m.AssetWorth);

                viewModel.CategoryInventoryAddCount = assetIQuery.Where(m => m.AssetCID == cateModel.CategoryID && m.AssetInventoryDetailID == 0).Count();
                viewModel.CategoryInventoryAddMoney = assetIQuery.Where(m => m.AssetCID == cateModel.CategoryID && m.AssetInventoryDetailID == 0).Sum(m => m.AssetPurchaseCost);

                viewModel.CategoryInventorySubCount = assetIQuery.Where(m => m.AssetCID == cateModel.CategoryID && m.AssetInventoryDetailID == 0).Count();
                viewModel.CategoryInventorySubMoney = assetIQuery.Where(m => m.AssetCID == cateModel.CategoryID && m.AssetInventoryDetailID == 0).Sum(m => m.AssetPurchaseCost);

                retViewList.Add(viewModel);

            }
             

            return View(retViewList);
        }




    }
}
